package com.link.base.base.sms.controller;

import com.link.base.sms.model.SmsAccntLine;
import com.link.base.user.model.CoreUser;
import com.link.base.base.sms.model.AccntGrouping;
import com.link.base.base.sms.model.SmsAccntLineDTO;
import com.link.base.base.sms.service.AccntGroupingService;
import com.link.base.base.sms.service.SmsAccntLineService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.modules.export.ExportFactory;
import com.link.core.modules.export.ExportWriter;
import com.link.core.modules.imports.ImportReader;
import com.link.core.modules.imports.ImportsFactory;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 线上和线下消费者相关controller
 *
 * @author 刘鲁
 * @date 2018/11/5 15:37
 */
@Controller
@RequestMapping("/link/smsAccntLine")
public class SmsAccntLineController extends BasicController<SmsAccntLine> {
    @Resource
    private SmsAccntLineService smsAccntLineService;
    @Resource
    private AccntGroupingService accntGroupingService;

    @Override
    public BasicService<SmsAccntLine> getBasicService() throws Exception {
        return smsAccntLineService;
    }

    /**
     * 根据条件查询记录,默认分页(若将'pageFlag'设置为'false'，则不分页)
     */
    @RequestMapping(value = "/accntqueryByExamplePage")
    @ResponseBody
    public Map<String, Object> selectByExamplePage(@JsonParam QueryParams qps,@JsonParam  SmsAccntLine entity, HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(6);
        try {
            qps.preDealSecurity(request);
            SmsAccntLine t = (SmsAccntLine) BasicModel.transformClass(entity, qps);
            beforQueryAllOrExample(t, request);
            beforQueryExample(t, request);
            t.setAcctType("ChannelConsumer");
            t.setPageFlag(false);
            List<SmsAccntLine> listFalse = new ArrayList<>();

            List<SmsAccntLine> listFa = getBasicService().queryByExamplePage(t);

            listFa = smsAccntLineService.isRepetition(listFalse, listFa);
            listFalse = smsAccntLineService.addlist(listFalse, listFa);
            List<SmsAccntLine> list = smsAccntLineService.accntLinePage(qps, listFalse);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", listFalse.size());
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SmsAccntLine>());
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SmsAccntLine>());
            result.put("result", e.getMessage());
        }
        return result;
    }


    @Override
    public void beforUpsert(SmsAccntLine entity, HttpServletRequest request) throws Exception {
        try {
            CoreUser landedUser = UserUtil.getUser();
            entity.setOrgId(landedUser.getOrgId());
            entity.setAcctChannel("OFFLINE");
        } catch (Exception e) {
            // TODO: handle exception
            LCLogger.withException(e);
        }
    }

    /**
     * 导出消费者模板
     */
    @Override
    @RequestMapping(value = "/accntqueryByExamplePage/exportData")
    @ResponseBody
    public Map<String, Object> exportData(SmsAccntLine entity, QueryParams qps, HttpSession session,
                                          HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> result = new HashMap<String, Object>(6);
        try {
            qps.preDealSecurity(request);
            ExportWriter exportWriter;
            exportWriter = ExportFactory.Excel2007Instance(qps);

            SmsAccntLine t = (SmsAccntLine) BasicModel.transformClass(entity, qps);
            while (!qps.getStopExport()) {

                beforQueryAllOrExample(t, request);
                beforQueryExample(t, request);
                List<SmsAccntLine> list = null;
                if (qps.getPage() == 1) {
                    qps.setTotal(t.getTotal());
                }
                exportWriter.wirteData(list);
                t.setPage(qps.getPage());
                t.setTotalFlag(qps.getTotalFlag());
            }
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 导入线下消费者
     */
    @Override
    @RequestMapping(value = "/importExcelData")
    @ResponseBody
    public Map<String, Object> importData(SmsAccntLine entity, QueryParams qps, HttpSession session,
                                          HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> result = new HashMap<String, Object>(7);
        try {
            ImportReader importReader = ImportsFactory.newInstance(qps, request);
            List<SmsAccntLine> list = (List<SmsAccntLine>) importReader.readList(entity.getClass());
            importExcelData(list, qps, request);
            result.put("success", true);
            result.put("total", list.size());
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    protected void importExcelData(List<SmsAccntLine> list, QueryParams qps, HttpServletRequest request)
            throws Exception {
        beforeImport(list, qps, request);
        for (int i = 0; list != null && i < list.size(); i++) {
            SmsAccntLine record = list.get(i);
            record.setAcctChannel("OFFLINE");
            record.setAcctType("CUSTOMER");
            SmsAccntLine existAccnt = smsAccntLineService.existAccnt(record);
            if (existAccnt != null) {
                smsAccntLineService.importAccntLineUpdate(record);
            } else {
                smsAccntLineService.insert(record);

            }
        }
    }

    /**
     * 导出
     */
    @RequestMapping(value = "/queryByExamplePage/smsExportData")
    @ResponseBody
    public Map<String, Object> smsExportData(@JsonParam AccntGrouping accntGrouping, QueryParams qps, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            qps.preDealSecurity(request);
            //添加逻辑，判断用户企业帐套的通用导出类型
            CoreUser user = UserUtil.getUser();
            ExportWriter exportWriter;
            String exportType = "xlsx";
            if (exportType.equals(user.getExportType())) {
                exportWriter = ExportFactory.newExcelInstance(qps);
            } else {
                exportWriter = ExportFactory.newInstance(qps);
            }
            SmsAccntLineDTO smsAccntLineDTO = new SmsAccntLineDTO();
            accntGroupingService.analysisConditionWithoutQps(accntGrouping, smsAccntLineDTO);
            QueryParams condiQps = smsAccntLineDTO.getQps();
            if (null != condiQps && !condiQps.getFilters().isEmpty()) {
                qps.setFilters(condiQps.getFilters());
            }
            BasicModel.transformClass(smsAccntLineDTO, qps);
            while (!qps.getStopExport()) {
                List<SmsAccntLine> list = smsAccntLineService.queryByFiltrateExamplePage(smsAccntLineDTO);
                if (qps.getPage() == 1) {
                    qps.setTotal(smsAccntLineDTO.getTotal());
                }
                exportWriter.wirteData(list);
                smsAccntLineDTO.setPage(qps.getPage());
                smsAccntLineDTO.setTotalFlag(qps.getTotalFlag());
            }
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
